{# itop-portal-base/portal/src/views/bricks/manage/layout.html.twig #}
{# Manage brick base layout #}
{% extends 'itop-portal-base/portal/src/views/bricks/layout.html.twig' %}

{% block pPageBodyClass %}{{ parent() }} page_manage_brick{% endblock %}

{% block pMainHeaderTitle %}
	{{ oBrick.GetTitle()|dict_s }}
{% endblock %}

{% block pMainHeaderActions %}
	{% if aGroupingTabsValues|length > 1 %}
		<div class="btn-group {#btn-group-sm#} btn_group_explicit">
			{% for aGroupingTab in aGroupingTabsValues %}
				<a href="{{ app.url_generator.generate('p_manage_brick', {'sBrickId': sBrickId, 'sGroupingTab': aGroupingTab.value}) }}" class="btn btn-default {% if sGroupingTab is defined and sGroupingTab == aGroupingTab.value %}active{% endif %}">{{ aGroupingTab.label|raw }}</a>
			{% endfor %}
		</div>
	{% endif %}
{% endblock %}

{% block pMainContentHolder%}
	{% set iTableCount = 0 %}
	{% if aGroupingAreasData|length > 0 %}
		{% for aAreaData in aGroupingAreasData %}
			{% if aAreaData.iItemsCount > 0 %}
				{% set iTableCount = iTableCount + 1 %}
				<div class="panel panel-default">
					<div class="panel-heading">
						<h3 class="panel-title">{{ aAreaData.sTitle }}</h3>
					</div>
					<div class="panel-body">
						{# We decided not to show empty tables anymore #}
						{#
						{% if aAreaData.iItemsCount > 0 %}
						#}
							<table id="table-{{ aAreaData.sId }}" class="table table-striped table-bordered responsive" width="100%"></table>
						{#
						{% else %}
							<div class="text-center">
								{{ 'Brick:Portal:Manage:Table:NoData'|dict_s }}
							</div>
						{% endif %}
						#}
					</div>
				</div>
			{% endif %}
		{% endfor %}
	{% endif %}
	
	{% if iTableCount == 0 %}
		<div class="panel panel-default">
			<div class="panel-body">
				<h3 class="text-center">{{ 'Brick:Portal:Manage:Table:NoData'|dict_s }}</h3>
			</div>
		</div>
	{% endif %}
{% endblock %}

{% block pPageLiveScripts %}
	{{ parent() }}
	
	<script type="text/javascript">
		var sDataLoading = '{{ sDataLoading }}';
		// Used for ajax throttling
		var iSearchThrottle = 300;
		var oKeyTimeout;
		var aKeyTimeoutFilteredKeys = [16, 17, 18, 19, 27, 33, 34, 35, 36, 37, 38, 39, 40]; // Shift, Ctrl, Alt, Pause, Esc, Page Up/Down, Home, End, Left/Up/Right/Down arrows
		
		var columnsProperties = {
			{% for aAreaData in aGroupingAreasData %}
				'{{ aAreaData.sId }}': {{ aAreaData.aColumnsDefinition|json_encode()|raw }},
			{% endfor %}
		};
		var rawData = {
			{% for aAreaData in aGroupingAreasData %}
				'{{ aAreaData.sId }}': {{ aAreaData.aItems|json_encode()|raw }},
			{% endfor %}
		};
		
		// Columns definition for the table from the columnsProperties
		var getColumnsDefinition = function(tableName)
		{
			var tableProperties = columnsProperties[tableName];
			
			if(tableProperties === undefined && window.console)
			{
				console.log('Could not retrieve columns properties for table "'+tableName+'"');
				return false;
			}
			if(rawData[tableName] === undefined && window.console)
			{
				console.log('Could not retrieve data for table "'+tableName+'"');
				return false;
			}
			
			var columnsDefinition = [];
			
			for(key in tableProperties)
			{
				columnsDefinition.push({
					"width": "auto",
					"searchable": true,
					"sortable": (sDataLoading === '{{ constant('Combodo\\iTop\\Portal\\Brick\\AbstractBrick::ENUM_DATA_LOADING_FULL') }}'),
					"title": tableProperties[key].title,
					"defaultContent": "",
					"type": "html",
					"data": "attributes."+key+".att_code",
					"render": function(att_code, type, row){
						var cellElem;
						var itemActions;
						var itemPrimarayAction;
						
						// Preparing action on the cell
						// Note : For now we will use only one action, the secondary actions are therefore not implemented. Only the data structure is done.
						itemActions = row.attributes[att_code].actions;
						
						// Preparing the cell data
						cellElem = (itemActions.length > 0) ? $('<a></a>') : $('<span></span>');
						cellElem.html(row.attributes[att_code].value);
						// Building actions
						if(itemActions.length > 0)
						{
							// - Primary action
							itemPrimaryAction = itemActions[0];
							switch(itemPrimaryAction.type)
							{
								case '{{ constant('Combodo\\iTop\\Portal\\Brick\\ManageBrick::ENUM_ACTION_VIEW') }}':
									url = '{{ app.url_generator.generate('p_object_view', {'sObjectClass': '-objectClass-', 'sObjectId': '-objectId-'})|raw }}'.replace(/-objectClass-/, itemPrimaryAction.class).replace(/-objectId-/, itemPrimaryAction.id);
									cellElem.attr('data-toggle', 'modal').attr('data-target', '#modal-for-all').attr('href', url);
									break;
								case '{{ constant('Combodo\\iTop\\Portal\\Brick\\ManageBrick::ENUM_ACTION_EDIT') }}':
									url = '{{ app.url_generator.generate('p_object_edit', {'sObjectClass': '-objectClass-', 'sObjectId': '-objectId-'})|raw }}'.replace(/-objectClass-/, itemPrimaryAction.class).replace(/-objectId-/, itemPrimaryAction.id);
									cellElem.attr('data-toggle', 'modal').attr('data-target', '#modal-for-all').attr('href', url);
									break;
								default:
									//console.log('Action "'+itemPrimaryAction+'" not implemented');
									break;
							}
							
							// - Secondary actions
							// Not done for now, only the data structure is ready in case we need it later
						}
						
						return cellElem.prop('outerHTML');
					},
				});
			}
			
			return columnsDefinition;
		};

		$(document).ready(function(){
			{% for aAreaData in aGroupingAreasData %}
				{% set sAreaId = aAreaData.sId %}
				var oTable{{ sAreaId }} = $('#table-{{ sAreaId }}').DataTable( {
					"language": {
						"processing":	  "{{ 'Portal:Datatables:Language:Processing'|dict_s }}",
						"search":		  "{{ 'Portal:Datatables:Language:Search'|dict_s }}",
						"lengthMenu":	  "{{ 'Portal:Datatables:Language:LengthMenu'|dict_s }}",
						"zeroRecords":	 "{{ 'Portal:Datatables:Language:ZeroRecords'|dict_s }}",
						"info":			"{{ 'Portal:Datatables:Language:Info'|dict_s }}",
						"infoEmpty":	   "{{ 'Portal:Datatables:Language:InfoEmpty'|dict_s }}",
						"infoFiltered":	"({{ 'Portal:Datatables:Language:InfoFiltered'|dict_s }})",
						"emptyTable":	  "{{ 'Portal:Datatables:Language:EmptyTable'|dict_s }}",
						"paginate": {
							"first":	  "{{ 'Portal:Datatables:Language:Paginate:First'|dict_s }}",
							"previous":   "{{ 'Portal:Datatables:Language:Paginate:Previous'|dict_s }}",
							"next":	   "{{ 'Portal:Datatables:Language:Paginate:Next'|dict_s }}",
							"last":	   "{{ 'Portal:Datatables:Language:Paginate:Last'|dict_s }}"
						},
						"aria": {
							"sortAscending":  ": {{ 'Portal:Datatables:Language:Sort:Ascending'|dict_s }}",
							"sortDescending": ": {{ 'Portal:Datatables:Language:Sort:Descending'|dict_s }}"
						}
					},
					"lengthMenu": [[10, 20, 50, -1], [10, 20, 50, "{{ 'Portal:Datatables:Language:DisplayLength:All'|dict_s }}"]],
					"displayLength": {{ constant('Combodo\\iTop\\Portal\\Brick\\ManageBrick::DEFAULT_COUNT_PER_PAGE_LIST') }},
					"dom": '<"row"<"col-sm-6"l><"col-sm-6"<f><"visible-xs"p>>>t<"row"<"col-sm-6"ri><"col-sm-6"p>>',
					"columns": getColumnsDefinition('{{ sAreaId }}'),
					"order": [[0, "desc"]],
					"rowCallback": function(oRow, oData){
						if(oData.highlight_class !== undefined)
						{
							var sHighlightClass = oData.highlight_class;
							var sBSHiglightClass = '';
							
							// Adding classic iTop class
							$(oRow).addClass(sHighlightClass);
							// Adding mapped BS class
							if(sHighlightClass === '{{ constant('HILIGHT_CLASS_CRITICAL') }}')
							{
								sBSHiglightClass = 'danger';
							}
							else if(sHighlightClass === '{{ constant('HILIGHT_CLASS_WARNING') }}')
							{
								sBSHiglightClass = 'warning';
							}
							else if(sHighlightClass === '{{ constant('HILIGHT_CLASS_OK') }}')
							{
								sBSHiglightClass = 'success';
							}
							$(oRow).addClass(sBSHiglightClass);
						}
					},
					"drawCallback": function(settings){
						// Hiding pagination if only one page
						if($(this).closest('.dataTables_wrapper').find('.dataTables_paginate:last .paginate_button:not(.previous):not(.next)').length < 2)
						{
							$(this).closest('.dataTables_wrapper').find('.dataTables_paginate, .dataTables_info').hide();
						}
						else
						{
							$(this).closest('.dataTables_wrapper').find('.dataTables_paginate, .dataTables_info').show();
						}
					},
					{% if sDataLoading == constant('Combodo\\iTop\\Portal\\Brick\\AbstractBrick::ENUM_DATA_LOADING_FULL') %}
						"data": rawData['{{ sAreaId }}'],
					{% else %}
						"processing": true,
						"serverSide": true,
						{#"searchDelay": 1000, // can be used to increase time between server calls when typing search query#}
						"ajax": {
							"url": "{{ app.url_generator.generate('p_manage_brick_lazy', {'sBrickId': sBrickId, 'sGroupingTab': sGroupingTab, 'sGroupingArea': sAreaId})|raw }}",
							"data": function(d){
								d.iPageNumber = Math.floor(d.start/d.length) + 1;
								d.iCountPerPage = d.length;
								d.columns = null;
								d.orders = null;
								if(d.search.value)
								{
									d.sSearchValue = d.search.value;
								}
							}
						}
					{% endif %}
				} );
				
				// Overrides filter input to apply throttle. Otherwise, an ajax request is send each time a key is pressed
				// Also removes accents from search string
				// Note : The '.off()' call is to unbind event from DataTables that where triggered before we could intercept anything
				$('#table-{{ sAreaId }}_filter input').off().on('keyup', function(){
					var me = this;

					clearTimeout(oKeyTimeout);
					oKeyTimeout = setTimeout(function() {
						oTable{{ sAreaId }}.search(me.value.latinise()).draw();
					}, iSearchThrottle);
				});
			{% endfor %}
		});
	</script>
{% endblock %}